package com.xkdx.guangguang.fragment.user;

import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.xkdx.caipiao.R;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.user.UserRegistModule.User;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;

public class UserRegisteFragment extends BaseFragment implements
		OnClickListener {

	/**
	 * finish 完成按钮,back回退按钮，userName快速注册用户名
	 */
	private Button finish, back;
	private EditText name;
	private ProgressDialog registLoading;

	private UserRegistPresenter presenter;
	private UserRegistModule module;
	private UserRegistAction actions;
	private View view;
	// public static String json;
	private User user;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.user_regist, container, false);

		findViews();

		return view;
	}

	/**
	 * 检查用户名是否为空
	 * 
	 * @return boolean
	 */
	private boolean checkTextView() {
		if (TextUtils.isEmpty(name.getText().toString())) {
			Toast.makeText(getActivity(), "用户名不能为空,请输入用户名", Toast.LENGTH_SHORT)
					.show();
			return false;
		}
		return true;

	}

	private void findViews() {
		name = (EditText) view.findViewById(R.id.name);
		finish = (Button) view.findViewById(R.id.user_regist_finish);
		back = (Button) view.findViewById(R.id.registe_back);
		finish.setOnClickListener(this);
		back.setOnClickListener(this);

		registLoading = new ProgressDialog(getActivity());
		registLoading.setMessage("用户注册中,请耐心等待...");
		registLoading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		registLoading.setCancelable(true);
		registLoading.setCanceledOnTouchOutside(false);// 解决4.0以上系统触屏后执行onCanel方法
		registLoading
				.setOnCancelListener(new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						getActivity().finish();
					}
				});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.registe_back:
			FragmentManager fm = getFragmentManager();
			fm.popBackStack();
			break;
		case R.id.user_regist_finish:
			if (!checkTextView()) {
				return;
			} else {
				// json = getJson(getActivity());
				showLoading();
			}
			break;
		default:
			break;
		}

	}

	@Override
	public void showLoading() {
		actions = new UserRegistAction(getActivity(), name.getText().toString());
		// actions.requestData = json.toString();
		module = new UserRegistModule(getActivity());
		presenter = new UserRegistPresenter(this);
		((ManagerActivity) getActivity()).addCurrentTask(presenter);
		presenter.setActitons(actions);
		presenter.setModule(module);
		presenter.execute();
		registLoading.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (presenter != null) {
					presenter.cancel(true);
				}
				getFragmentManager().popBackStack();

			}
		});
		registLoading.show();

	}

	// String MobilePhone;
	// // 获取登录注册字符串
	// public String getJson(Context context) {
	// // 获取手机号
	// TelephonyManager mTelephonyManager = (TelephonyManager) context
	// .getSystemService(context.TELEPHONY_SERVICE);
	// MobilePhone = mTelephonyManager.getLine1Number();
	// // 获取设备串号
	// String DeviceSN = mTelephonyManager.getDeviceId();
	// // 获取设备型号
	// String DeviceModel = Build.MODEL;
	// // 获取系统版本
	// String OSVersion = Build.VERSION.SDK;
	//
	// StringBuilder builder = new StringBuilder();
	// builder.append("{\"").append("DeviceID").append("\":").append("2")
	// .append(",").append("\"RegionID\":").append("\"D0101\",")
	// .append("\"LoginID\":\"").append(name.getText().toString())
	// .append("\",").append("\"Password\":").append("\"")
	// .append("123456").append("\",").append("\"NickName\":")
	// .append("\"").append(name.getText().toString()).append("\",")
	// .append("\"MobilePhone\":").append("\"").append(MobilePhone)
	// .append("\",").append("\"DeviceSN\":").append("\"")
	// .append(DeviceSN).append("\",").append("\"DeviceModel\":")
	// .append("\"").append(DeviceModel).append("\",")
	// .append("\"OSVersion\":").append("\"").append(OSVersion)
	// .append("\"}");
	// return builder.toString();
	// }

	public void showLoaded(HashMap<String, AbsModule> msg) {
		if (registLoading != null && registLoading.isShowing()) {
			registLoading.dismiss();
		}

		if (msg.containsKey("0")) {
			user = ((UserRegistModule) msg.get("0")).user;
			if (user != null && user.getStatus() != null
					&& user.getStatus().equals("Success")) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						getActivity());
				builder.setTitle("注册成功");
				builder.setMessage("您的初始密码是:123456,请及时修改密码!");
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								IConstants.IsDisEnable = false;
								FragmentTransaction ft = getFragmentManager()
										.beginTransaction();
								UserLoginSuccessFragment sucessLoginFragment = new UserLoginSuccessFragment();
								Bundle b = new Bundle();
								b.putSerializable("user", user);
								sucessLoginFragment.setArguments(b);
								ft.replace(R.id.fragment, sucessLoginFragment,
										"userLoginSuccessFragment")
										.addToBackStack(null).commit();
							}
						});
				builder.create().show();
			} else {
				Toast.makeText(getActivity(), user.getMessage(), 0).show();
			}

		} else {
			showErrorTip(msg);
		}

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void findView() {
		// TODO Auto-generated method stub

	}

	@Override
	public void setOnClick() {
		// TODO Auto-generated method stub

	}

	// @Override
	// public void showRefresh(HashMap<String, AbsModule> map) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void showLoadMore(HashMap<String, AbsModule> map) {
	// // TODO Auto-generated method stub
	//
	// }

}
